package com.gnerv.sylvanas.plugin.actuator.autoconfigure;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Gnerv LiGen
 */
@Slf4j
@Service
public class ActuatorEnvironmentPostProcessor implements EnvironmentPostProcessor {

    private static final String NAME = "PluginActuatorProperties";
    private static final Map<Object, Object> ENVIRONMENT = new ConcurrentHashMap<>();

    static {
        ENVIRONMENT.put("management.server.port", 19000);
        ENVIRONMENT.put("management.endpoints.web.base-path", "/api/monitor/actuator");
        ENVIRONMENT.put("management.metrics.export.prometheus.enabled", true);
        ENVIRONMENT.put("management.endpoints.web.exposure.include", "health,info,metrics,prometheus");
    }

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        String port = environment.getProperty("management.server.port");
        if (StringUtils.hasText(port)) {
            ENVIRONMENT.put("management.server.port", port);
        }
        String basePath = environment.getProperty("management.endpoints.web.base-path");
        if (StringUtils.hasText(basePath)) {
            ENVIRONMENT.put("management.endpoints.web.base-path", basePath);
        }
        String prometheus = environment.getProperty("management.metrics.export.prometheus.enabled");
        if (StringUtils.hasText(prometheus)) {
            ENVIRONMENT.put("management.metrics.export.prometheus.enabled", prometheus);
        }
        String include = environment.getProperty("management.endpoints.web.exposure.include");
        if (StringUtils.hasText(include)) {
            ENVIRONMENT.put("management.endpoints.web.exposure.include", include);
        }
        Properties properties = new Properties();
        properties.putAll(ENVIRONMENT);
        PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource(NAME, properties);
        environment.getPropertySources().addLast(propertiesPropertySource);
        log.info("Actuator environment post process finished");
    }
}
